package com.boxin.ims.modules.wechat.utils;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.boxin.ims.modules.wechat.entity.JiuWechatMember;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.JiuWechatMemberService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.JedisUtils;

/**
 * @author Administrator
 * @date 2015-11-26
 * @function <p> 数据缓存 </p>
 */
@Service
public class WechatCacheUtils implements ApplicationContextAware{
	
	
	private static JiuWechatMemberService jiuWechatMemberService;
	private static WeChatService weChatService;
	
	
	
	
	/**
	 * 会员信息缓存，注意，缓存对象有可能不是最新的信息数据
	 * @param userId
	 * @param wechatId
	 * @return
	 */
	public static JiuWechatMember getWechatMemberByOpenId(Long userId,String wechatId){
		Object object = CacheUtils.get(wechatId);
		if(object!=null){
			return (JiuWechatMember) object;
		}else{
			JiuWechatMember wechatMember = jiuWechatMemberService.getByUserIdAndOpenId(userId, wechatId);
			System.out.println(wechatMember.getNickname()+"==============nicknaeme ===========================");
			if(wechatMember!=null){
				CacheUtils.put(wechatId, wechatMember);
			}
			return wechatMember;
		}
	}
	
	
	
	
	
	/**
	 * @author Jakemanse
	 * @time 2015-11-27  上午12:28:19
	 * @function <p>获取微信Token配置  </p>
	 * @param id
	 * @return
	 */
	public static WeChat getWechatById(Long id){
		String key = "wechat_cache_"+id+"";
		Object object = CacheUtils.get(key);
		if(object!=null){
			return (WeChat) object;
		}else{
			WeChat wechat = weChatService.get(id);
			CacheUtils.put(key, wechat);
			return wechat;
		}
	}





	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		
		jiuWechatMemberService = (JiuWechatMemberService)applicationContext.getBean("jiuWechatMemberService");
		weChatService = (WeChatService)applicationContext.getBean("weChatService");
		/*jiuDesignService = (JiuDesignService)applicationContext.getBean("jiuDesignService");
		jiuFinanceService = (JiuFinanceService)applicationContext.getBean("jiuFinanceService");*/
	}
	
	/**
	 * 获取微信Token配置  
	 * @param userId
	 * @return
	 */
	public static WeChat getWeChatByUserId(Long userId){
		String key = "wechat_cache_userid_"+userId+"";
		Object object = JedisUtils.getObject(key);
		if(object!=null){
			return (WeChat) object;
		}else{
			WeChat wechat = weChatService.getWeChatByUserId(userId);
			JedisUtils.setObject(key, wechat, 0);
			return wechat;
		}
	}
}

